//
//  NSString+Safe.m
//  DebugDemo
//
//  Created by XFB on 2018/11/9.
//  Copyright © 2018年 ZhouCheng. All rights reserved.
//

#import "NSString+Safe.h"
#import "NSObject+Swizzling.h"

///// 不可变字符串
//static NSString *KStringClass = @"__NSCFString";

@implementation NSString (Safe)

+ (void)load
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{ 
        [objc_getClass("__NSCFString") swizzleSelector:@selector(characterAtIndex:)
                                     withSwizzledSelector:@selector(zc_safeCharacterAtIndex:)];
        [objc_getClass("__NSCFString") swizzleSelector:@selector(substringWithRange:)
                                  withSwizzledSelector:@selector(zc_safeSubstringWithRange:)];
        [objc_getClass("__NSCFString") swizzleSelector:@selector(substringFromIndex:)
                                  withSwizzledSelector:@selector(zc_safeSubstringFromIndex:)];
        [objc_getClass("__NSCFString") swizzleSelector:@selector(substringToIndex:)
                                  withSwizzledSelector:@selector(zc_safeSubstringToIndex:)];
        [objc_getClass("__NSCFString") swizzleSelector:@selector(rangeOfString:)
                                  withSwizzledSelector:@selector(zc_safeRangeOfString:)];
    });
}

- (unichar)zc_safeCharacterAtIndex:(NSUInteger)index
{
    if(index >= self.length) return 0;
    return [self zc_safeCharacterAtIndex:index];
}

- (NSString *)zc_safeSubstringWithRange:(NSRange)range
{
    if(range.location + range.length > self.length) return @"";
    return [self zc_safeSubstringWithRange:range];
}

- (NSString *)zc_safeSubstringFromIndex:(NSUInteger)from
{
    if(from > self.length) return @"";
    return [self zc_safeSubstringFromIndex:from];
}

- (NSString *)zc_safeSubstringToIndex:(NSUInteger)to
{
    if(to > self.length) return self;
    return [self zc_safeSubstringToIndex:to];
}

- (NSRange)zc_safeRangeOfString:(NSString *)searchString
{
    if(!searchString) return NSMakeRange(0, 0);
    return [self zc_safeRangeOfString:searchString];
}

@end
